#—*- coding:utf-8 -*-
#!/usr/bin/python
import requests
import traceback
import json
import urllib2
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
def api_v3(setting,apiname,params,retry=0):
    UserName = setting.get("User-Name","bw_api_v3")
    AccessToken = setting.get("Access-Token","bw_api_v3")
    baseUrl = setting.get("baseurl","bw_api_v3")
    session = requests.session()
    session.headers.update({
        "User-Name": UserName,
        "Access-Token":AccessToken
    })
    try:
        # print baseUrl+apiname
        # print params
        resText = session.get(baseUrl+apiname, params=params, verify=False).text

        setting.log.warning("api_v3: url:%s params:%s respons:%s"%(baseUrl+apiname,json.dumps(params),resText))
        if resText:
            res = json.loads(resText)
        else:
            raise 'api没有返回结果'
    except :
        err = traceback.format_exc()
        setting.log.warning("api_v3_err:  url:%s params:%s error:%s"%(baseUrl+apiname,json.dumps(params),err))
        res = {"status": {"msg": "request error","code": 505}}
    if res['status']['code'] != 200 and retry > 0:
        return api_v3(setting,apiname,params,retry-1)
    else:
        if res['status']['code'] == 200:
            return res['data']
        else:
            return False
"""存储今日慧评分"""
def save_yest_bwscore(setting,hotelid,time,bwscore,areaid):

    url = setting.get("url","process_api")
    reqHeader = {"Content-Type": "application/json"}
    data = {"HotelID":hotelid,"Time":time,"BWScore":bwscore}
    if areaid:
        data['AreaId'] = areaid
    try:
        postDataString = json.dumps(data)
        request = urllib2.Request(url, postDataString, reqHeader)
        # reqTimeOut为超时时间，不设置可以不传

        request.get_method = lambda: 'PUT'
        response = urllib2.urlopen(request,timeout=3)
        rs = response.read()
        rsData = json.loads(rs)
        setting.log.warning("save_yest_bwscore: url:%s params:%s respons:%s"%(url,postDataString,rs))
        return rsData
    except:
        err = traceback.format_exc()
        setting.log.warning("save_yest_bwscore_err:  url:%s params:%s error:%s"%(url,json.dumps(data),err))
        return None

"""问卷接口"""
def gss_api(setting,hotelid,stime,etime,retry=0):
    baseUrl = setting.get("baseurl","gss_api")
    session = requests.session()
    url = baseUrl + "/statistics/score/hid/%s/stime/%s/etime/%s"%(hotelid,stime,etime)
    try:
        res = session.get(url).json()
        setting.log.warning("gss_api:  url:%s  respons:%s"%(url,json.dumps(res)))
        return res['AnswerCount'],res['lowerScorCount']
    except:
        err = traceback.format_exc()
        setting.log.warning("gss_api_err:  url:%s  error:%s"%(url,err))

        if retry > 0:
            return gss_api(setting,hotelid,stime,etime,retry-1)
        else:
            return -1,-1
    #http://t-gss.brandwisdom.cn/statistics/score/hid/100121/stime/1509206400/etime/1509292800
"""市场热度接口"""
def otb_event_api(setting,hotelid,retry=0):
    baseUrl = setting.get("event","otb_api")
    session = requests.session()
    url = baseUrl+'?hotelid=%s'%(hotelid)
    try:
        res = session.get(url).json()
        setting.log.warning("otb_event_api:  url:%s  respons:%s"%(url,json.dumps(res)))
        if res['status']['code'] == "200" and 'data' in res and 'total' in res['data']:
            return res['data']['total'],res['data']['cityareaname'],res['data']['cityareanameEn']
        else:
            if retry > 0:
                return otb_event_api(setting,hotelid,retry -1)
            else:
                return -1,'',''
    except:
        err = traceback.format_exc()
        setting.log.warning("otb_event_api_err:  url:%s  error:%s"%(url,err))
        if retry > 0:
            return otb_event_api(setting,hotelid,retry -1)
        else:
            return -1,'',''
"""otb市场需求热度同比"""
def otb_heat_rate(setting,hotelid,retry=0):
    baseUrl = setting.get("heat_rate","otb_api")
    session = requests.session()
    url = baseUrl+'?hotelid=%s'%(hotelid)
    #{"CityCn":"北京","CityEn":"beijing","Start":3,"HheatRate":0.61}
    try:
        res = session.get(url).json()
        setting.log.warning("otb_heat_rate:  url:%s  respons:%s"%(url,json.dumps(res)))
        if res['status']['code'] == "200":
            return {"CityCn":res['data']['cityname'],
                    "CityEn":res['data']['citynameEn'],
                    'Start':res['data']['hotelStar'],
                    'HheatRate':res['data']['heatRate'][:-1]}

        else:
            if retry > 0:
                return otb_heat_rate(setting,hotelid,retry -1)
            else:
                return None
    except:
        err = traceback.format_exc()
        setting.log.warning("otb_heat_rate_err:  url:%s  error:%s"%(url,err))
        if retry > 0:
            return otb_heat_rate(setting,hotelid,retry -1)
        else:
            return None

def wechat_message(setting,data,retry=0):

    url = setting.get("notic_url","wechat")
    try:
        session = requests.session()
        res = session.post(url,data=data,timeout=10).json()
        setting.log.warning("wechat_message:  url:%s data:%s respons:%s"%(url,json.dumps(data),json.dumps(res)))
        if res['code'] == "0000":
            return res
        else:
            setting.log.warning(json.dumps(res))
            if retry > 0:
                return wechat_message(setting,data,retry -1)
            else:
                return res
    except Exception,e:
        err = traceback.format_exc()
        setting.log.error("wechat_message_err:  url:%s data:%s error:%s"%(url,json.dumps(data),err))
        if retry > 0:
            return wechat_message(setting,data,retry -1)
        else:
            return {"code":'00001',"errmessage":e.message}
